<template>
  <view class="order-review-container">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

    <!-- 自定义导航栏 -->
    <view class="top-nav">
      <view class="nav-left" @click="goBack">
        <text class="back-icon">←</text>
      </view>
      <view class="nav-center">
        <text class="nav-title">评价订单</text>
      </view>
      <view class="nav-right"></view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 评价表单 -->
    <view v-else class="review-form">
      <!-- 商品信息卡片 -->
      <view v-if="orderInfo" class="order-info-card">
        <view class="merchant-info">
          <text class="icon">🏪</text>
          <text class="merchant-name">{{ orderInfo.merchantName }}</text>
        </view>
        <view class="food-info">
          <image 
            v-if="orderInfo.items && orderInfo.items[0]" 
            :src="orderInfo.items[0].foodImage" 
            class="food-image"
            mode="aspectFill"
          />
          <view class="food-details">
            <text class="food-name">{{ orderInfo.items && orderInfo.items[0] ? orderInfo.items[0].foodName : '' }}</text>
            <text class="food-price">¥{{ orderInfo.totalAmount }}</text>
          </view>
        </view>
      </view>

      <!-- 综合评分 -->
      <view class="rating-section">
        <view class="section-header">
          <text class="section-title">综合评分</text>
          <text class="required">*</text>
        </view>
        <view class="rating-stars">
          <StarRating 
            :value="form.overallRating" 
            :size="60"
            @change="handleOverallRatingChange"
          />
          <text class="rating-text">{{ getRatingText(form.overallRating) }}</text>
        </view>
      </view>

      <!-- 详细评分 -->
      <view class="detail-rating-section">
        <view class="rating-item">
          <text class="rating-label">口味评分</text>
          <StarRating 
            :value="form.tasteRating" 
            :size="48"
            @change="(val) => form.tasteRating = val"
          />
        </view>
        <view class="rating-item">
          <text class="rating-label">速度评分</text>
          <StarRating 
            :value="form.speedRating" 
            :size="48"
            @change="(val) => form.speedRating = val"
          />
        </view>
        <view class="rating-item">
          <text class="rating-label">包装评分</text>
          <StarRating 
            :value="form.packageRating" 
            :size="48"
            @change="(val) => form.packageRating = val"
          />
        </view>
      </view>

      <!-- 评价标签 -->
      <view class="tags-section">
        <view class="section-header">
          <text class="section-title">评价标签</text>
        </view>
        <view class="tags-list">
          <view 
            v-for="(tag, index) in tagOptions" 
            :key="index"
            class="tag-item"
            :class="{ active: form.tags.includes(tag) }"
            @click="toggleTag(tag)"
          >
            <text class="tag-text">{{ tag }}</text>
          </view>
        </view>
      </view>

      <!-- 评价内容 -->
      <view class="content-section">
        <view class="section-header">
          <text class="section-title">评价内容</text>
          <text class="char-count">{{ form.content.length }}/500</text>
        </view>
        <textarea 
          v-model="form.content"
          class="content-textarea"
          placeholder="说说你的用餐感受..."
          :maxlength="500"
          placeholder-style="color: #999;"
        />
      </view>

      <!-- 上传图片 -->
      <view class="images-section">
        <view class="section-header">
          <text class="section-title">上传图片</text>
          <text class="image-count">({{ form.images.length }}/9)</text>
        </view>
        <view class="images-grid">
          <view 
            v-for="(image, index) in form.images" 
            :key="'img-' + index"
            class="image-item"
          >
            <image :src="image" class="preview-image" mode="aspectFill" />
            <view class="delete-btn" @click="deleteImage(index)">
              <text class="delete-icon">×</text>
            </view>
          </view>
          <view 
            v-if="form.images.length < 9"
            class="image-item add-image"
            @click="chooseImage"
          >
            <text class="add-icon">+</text>
            <text class="add-text">添加图片</text>
          </view>
        </view>
      </view>

      <!-- 匿名选项 -->
      <view class="anonymous-section">
        <view class="anonymous-option" @click="form.isAnonymous = !form.isAnonymous">
          <text class="checkbox">{{ form.isAnonymous ? '☑' : '☐' }}</text>
          <text class="option-text">匿名评价</text>
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="submit-section">
        <button class="cancel-btn" @click="goBack">取消</button>
        <button class="submit-btn" @click="submitReview">提交评价</button>
      </view>
    </view>

    <!-- 自定义Modal -->
    <CustomModal ref="customModal" />
  </view>
</template>

<script>
import StarRating from '@/components/StarRating.vue';
import CustomModal from '@/components/CustomModal.vue';
import orderService from '@/services/order.js';
import reviewService from '@/services/review.js';

export default {
  components: {
    StarRating,
    CustomModal
  },
  data() {
    return {
      statusBarHeight: 0,
      orderId: null,
      orderInfo: null,
      loading: true,
      form: {
        overallRating: 5,
        tasteRating: 5,
        speedRating: 5,
        packageRating: 5,
        content: '',
        images: [],
        tags: [],
        isAnonymous: false
      },
      tagOptions: [
        '味道不错', '分量足', '包装好', '送得快',
        '服务好', '性价比高', '很新鲜', '会再来'
      ]
    };
  },
  onLoad(options) {
    // 获取状态栏高度
    const systemInfo = uni.getSystemInfoSync();
    this.statusBarHeight = systemInfo.statusBarHeight || 0;
    
    // 设置CSS变量
    if (typeof document !== 'undefined') {
      document.documentElement.style.setProperty('--status-bar-height', this.statusBarHeight + 'px');
    }

    // 获取订单ID
    this.orderId = options.orderId;
    if (!this.orderId) {
      uni.showToast({ title: '订单ID不存在', icon: 'none' });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
      return;
    }

    this.loadOrderInfo();
  },
  computed: {
    // 判断是否可以返回
    canGoBack() {
      const pages = getCurrentPages();
      return pages.length > 1;
    }
  },
  methods: {
    // 加载订单信息
    async loadOrderInfo() {
      try {
        this.loading = true;
        const res = await orderService.getOrderDetail(this.orderId);
        this.orderInfo = res.data;
        
        // 检查订单状态
        if (this.orderInfo.status !== 'delivered') {
          uni.showToast({ title: '只能评价已完成的订单', icon: 'none' });
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        }
      } catch (error) {
        console.error('加载订单信息失败:', error);
        uni.showToast({ title: '加载失败', icon: 'none' });
      } finally {
        this.loading = false;
      }
    },

    // 返回
    goBack() {
      if (this.canGoBack) {
        uni.navigateBack();
      } else {
        // 如果是直接访问或刷新后，跳转到订单列表
        uni.reLaunch({
          url: '/pages/orders/orders'
        });
      }
    },

    // 综合评分改变
    handleOverallRatingChange(value) {
      this.form.overallRating = value;
    },

    // 获取评分文字
    getRatingText(rating) {
      const texts = ['', '非常差', '差', '一般', '满意', '非常满意'];
      return texts[rating] || '';
    },

    // 切换标签
    toggleTag(tag) {
      const index = this.form.tags.indexOf(tag);
      if (index > -1) {
        this.form.tags.splice(index, 1);
      } else {
        this.form.tags.push(tag);
      }
    },

    // 选择图片
    async chooseImage() {
      try {
        const res = await uni.chooseImage({
          count: 9 - this.form.images.length,
          sizeType: ['compressed'], // 压缩图片
          sourceType: ['album', 'camera']
        });

        uni.showLoading({ title: '上传中...' });

        // 上传图片
        let successCount = 0;
        let failCount = 0;
        
        for (let filePath of res.tempFilePaths) {
          try {
            const uploadRes = await this.uploadImage(filePath);
            this.form.images.push(uploadRes);
            successCount++;
          } catch (error) {
            console.error('上传图片失败:', error);
            failCount++;
          }
        }

        uni.hideLoading();
        
        // 显示上传结果
        if (successCount > 0) {
          uni.showToast({ 
            title: `成功上传${successCount}张图片${failCount > 0 ? `，${failCount}张失败` : ''}`, 
            icon: 'success',
            duration: 2000
          });
        } else if (failCount > 0) {
          uni.showToast({ 
            title: '图片上传失败，请重试', 
            icon: 'none',
            duration: 2000
          });
        }
      } catch (error) {
        console.error('选择图片失败:', error);
        uni.hideLoading();
      }
    },

    // 上传图片到OSS
    uploadImage(filePath) {
      return new Promise((resolve, reject) => {
        const token = uni.getStorageSync('jwt_token');
        
        console.log('📤 开始上传图片:', filePath);
        console.log('🔑 Token:', token ? '已设置' : '未设置');
        
        uni.uploadFile({
          url: 'http://localhost:8080/api/v1/upload/image',
          filePath: filePath,
          name: 'file',  // 修复：后端需要的参数名是 'file'，不是 'image'
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: (res) => {
            console.log('📥 上传响应:', res);
            
            if (res.statusCode === 200) {
              try {
                const data = JSON.parse(res.data);
                if (data.code === 200) {
                  console.log('✅ 上传成功:', data.data.url);
                  resolve(data.data.url);
                } else {
                  console.error('❌ 上传失败:', data.message);
                  reject(new Error(data.message || '上传失败'));
                }
              } catch (error) {
                console.error('❌ 解析响应失败:', error);
                reject(new Error('解析响应失败'));
              }
            } else {
              console.error('❌ HTTP错误:', res.statusCode, res.data);
              // 尝试解析错误信息
              try {
                const errorData = JSON.parse(res.data);
                reject(new Error(errorData.message || `上传失败(${res.statusCode})`));
              } catch {
                reject(new Error(`上传失败(${res.statusCode})`));
              }
            }
          },
          fail: (error) => {
            console.error('❌ 上传请求失败:', error);
            reject(error);
          }
        });
      });
    },

    // 删除图片
    deleteImage(index) {
      this.form.images.splice(index, 1);
    },

    // 提交评价
    async submitReview() {
      // 验证
      if (this.form.overallRating === 0) {
        uni.showToast({ title: '请选择综合评分', icon: 'none' });
        return;
      }

      try {
        uni.showLoading({ title: '提交中...' });

        await reviewService.createReview({
          orderId: this.orderId,
          overallRating: this.form.overallRating,
          tasteRating: this.form.tasteRating,
          speedRating: this.form.speedRating,
          packageRating: this.form.packageRating,
          content: this.form.content,
          images: this.form.images,
          tags: this.form.tags,
          isAnonymous: this.form.isAnonymous
        });

        uni.hideLoading();

        this.$refs.customModal.show({
          title: '评价成功',
          content: '感谢您的评价！',
          type: 'success',
          showCancel: false,
          confirmText: '确定',
          onConfirm: () => {
            uni.navigateBack();
          }
        });
      } catch (error) {
        uni.hideLoading();
        console.error('提交评价失败:', error);
        uni.showToast({ 
          title: error.message || '提交失败', 
          icon: 'none' 
        });
      }
    }
  }
};
</script>

<style scoped>
.order-review-container {
  min-height: 100vh;
  background: #F5F5F5;
  --status-bar-height: 0;
}

/* 状态栏 */
.status-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #FFFFFF;
  z-index: 999;
}

/* 导航栏 */
.top-nav {
  position: fixed;
  top: var(--status-bar-height);
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 30rpx;
  background: #FFFFFF;
  border-bottom: 1rpx solid #EEEEEE;
  z-index: 998;
}

.nav-left, .nav-right {
  width: 120rpx;
}

.back-icon {
  font-size: 40rpx;
  color: #333333;
}

.nav-center {
  flex: 1;
  text-align: center;
}

.nav-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333333;
}

/* 加载状态 */
.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 600rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #999999;
}

/* 评价表单 */
.review-form {
  margin-top: 88rpx; /* 导航栏高度 */
  padding-bottom: 200rpx;
}

/* 商品信息卡片 */
.order-info-card {
  margin: 20rpx 30rpx;
  padding: 30rpx;
  background: #FFFFFF;
  border-radius: 16rpx;
}

.merchant-info {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 24rpx;
}

.icon {
  font-size: 32rpx;
}

.merchant-name {
  font-size: 30rpx;
  font-weight: 600;
  color: #333333;
}

.food-info {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.food-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
}

.food-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.food-name {
  font-size: 32rpx;
  color: #333333;
}

.food-price {
  font-size: 36rpx;
  font-weight: 600;
  color: #FF6B6B;
}

/* 评分区域 */
.rating-section {
  margin: 20rpx 30rpx;
  padding: 30rpx;
  background: #FFFFFF;
  border-radius: 16rpx;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
}

.required {
  color: #FF6B6B;
  margin-left: 8rpx;
}

.rating-stars {
  display: flex;
  align-items: center;
  gap: 24rpx;
}

.rating-text {
  font-size: 28rpx;
  color: #666666;
}

/* 详细评分 */
.detail-rating-section {
  margin: 20rpx 30rpx;
  padding: 30rpx;
  background: #FFFFFF;
  border-radius: 16rpx;
}

.rating-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #F5F5F5;
}

.rating-item:last-child {
  border-bottom: none;
}

.rating-label {
  font-size: 30rpx;
  color: #333333;
}

/* 标签区域 */
.tags-section {
  margin: 20rpx 30rpx;
  padding: 30rpx;
  background: #FFFFFF;
  border-radius: 16rpx;
}

.tags-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.tag-item {
  padding: 16rpx 32rpx;
  background: #F5F5F5;
  border-radius: 40rpx;
  border: 2rpx solid transparent;
  transition: all 0.3s ease;
}

.tag-item.active {
  background: #FFF5F5;
  border-color: #FF6B6B;
}

.tag-text {
  font-size: 28rpx;
  color: #666666;
}

.tag-item.active .tag-text {
  color: #FF6B6B;
}

/* 内容区域 */
.content-section {
  margin: 20rpx 30rpx;
  padding: 30rpx;
  background: #FFFFFF;
  border-radius: 16rpx;
}

.char-count {
  font-size: 24rpx;
  color: #999999;
}

.content-textarea {
  width: 100%;
  min-height: 200rpx;
  padding: 20rpx;
  margin-top: 16rpx;
  background: #F8F8F8;
  border-radius: 12rpx;
  font-size: 28rpx;
  color: #333333;
  line-height: 1.6;
}

/* 图片区域 */
.images-section {
  margin: 20rpx 30rpx;
  padding: 30rpx;
  background: #FFFFFF;
  border-radius: 16rpx;
}

.image-count {
  font-size: 24rpx;
  color: #999999;
}

.images-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-top: 16rpx;
}

.image-item {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  border-radius: 12rpx;
  overflow: hidden;
}

.preview-image {
  width: 100%;
  height: 100%;
}

.delete-btn {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  width: 48rpx;
  height: 48rpx;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.delete-icon {
  font-size: 36rpx;
  color: #FFFFFF;
  line-height: 1;
}

.add-image {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #F8F8F8;
  border: 2rpx dashed #DDDDDD;
}

.add-icon {
  font-size: 60rpx;
  color: #999999;
  line-height: 1;
}

.add-text {
  font-size: 24rpx;
  color: #999999;
  margin-top: 8rpx;
}

/* 匿名选项 */
.anonymous-section {
  margin: 20rpx 30rpx;
  padding: 30rpx;
  background: #FFFFFF;
  border-radius: 16rpx;
}

.anonymous-option {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.checkbox {
  font-size: 40rpx;
  color: #FF6B6B;
}

.option-text {
  font-size: 30rpx;
  color: #333333;
}

/* 提交按钮 */
.submit-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  gap: 20rpx;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  background: #FFFFFF;
  border-top: 1rpx solid #EEEEEE;
}

.cancel-btn {
  flex: 1;
  height: 88rpx;
  background: #F5F5F5;
  border: none;
  border-radius: 44rpx;
  font-size: 32rpx;
  color: #666666;
}

.submit-btn {
  flex: 2;
  height: 88rpx;
  background: linear-gradient(135deg, #FF6B6B 0%, #FF8E8E 100%);
  border: none;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: 600;
  color: #FFFFFF;
}
</style>

